<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/12/14 9:05
 * Desc: 景点人群配置
 */
class Model_Spot_People_Group extends ORM
{

    protected $_table_name = 'spot_people_group';

    /**
     *  删除一个人群
     * @param $id
     * @return void
     * @throws Exception
     */
    public static function del($id)
    {
        $people = DB::select()
            ->from('spot_people_group')
            ->where('id', '=', $id)
            ->execute()
            ->current();

        if (!$people) {
            throw new Exception('人群不存在，请刷新后重试');
        }

        if ($people['is_system'] == 1) {
            throw new Exception('不允许删除系统配置人群');
        }

        DB::delete('spot_people_group')->where('id', '=', $id)->execute();

        // 删除人群关联
        Model_Spot_People_Config::del_by_group_id($id);

        // 删除景点门票关联
        Model_Spot_Ticket_People_Rule::del_by_group_id($id);
    }

    /**
     * 新增一个人群
     * @param string $name
     * @return void
     * @throws Kohana_Exception
     */
    public static function add_people(string $name = '默认人群')
    {
        $data = array('name' => $name, 'addtime' => time(), 'is_show' => 1);
        DB::insert('spot_people_group', array_keys($data))->values(array_values($data))->execute();
    }

    /**
     * 更新人群数据
     * @return bool
     */
    public static function update_people($id, $data)
    {
        $data['modtime'] = time();
        $result          = DB::update('spot_people_group')->where('id', '=', $id)->set($data)->execute();
        return (boolean)$result;
    }
}